package gitlet;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JFileChooser;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.List;

import static gitlet.Utils.readHistory;

/**
 * @Description MainFrame类是JFrame的子类，用于创建一个主窗口。这个窗口包含一个菜单栏和一个分割面板。菜单栏包含"Init"和"Helper"两个菜单，"Init"菜单包含"选择"、"历史项目"和"退出"三个菜单项。分割面板的上半部分是一个滚动面板，下半部分是一个文本区域。
 * @author 陈恒康
 * @date 2023/12/23
 */
public class MainFrame extends JFrame {

    private String[] branches;
    private Repository repo;
    private String path;
    private final JPanel docPanel;
    private final JPanel branchPanel;

    /**
     *@Description 构造一个新的MainFrame对象。该对象包含一个菜单栏和一个分割面板。菜单栏包含"Init"和"Helper"两个菜单，"Init"菜单包含"选择"、"历史项目"和"退出"三个菜单项。分割面板的上半部分是一个滚动面板，下半部分是一个文本区域。
     *@param title 窗口的标题
     */
    public MainFrame(String title) {
        super(title);
        this.setLayout(new BorderLayout());
        JPanel rootPanel = new JPanel();
        rootPanel.setLayout(new BorderLayout());
        rootPanel.setSize(800, 300);
        docPanel = new JPanel();
        docPanel.setSize(800, 300);
        branchPanel = new JPanel();
        rootPanel.add(docPanel, BorderLayout.CENTER);
        rootPanel.add(branchPanel, BorderLayout.SOUTH);
        this.add(rootPanel, BorderLayout.WEST);

        PanelJTextArea textArea = new PanelJTextArea();
        JTextArea jTextArea = new JTextArea();
        JScrollPane textPanel = new JScrollPane(textArea);
        textPanel.setPreferredSize(new Dimension(800, 100));
        textPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setTopComponent(textPanel);
        splitPane.setBottomComponent(jTextArea);

        JMenuBar jMenuBar = new JMenuBar();
        JMenu initMenu = new JMenu("Init");
        JMenu helper = new JMenu("Helper");
        jMenuBar.add(initMenu);
        jMenuBar.add(helper);
        this.add(splitPane, BorderLayout.CENTER);

        splitPane.setResizeWeight(1.0);
        JMenuItem chooseFileButton = new JMenuItem("选择");
        JMenuItem chooseHistoryFile = new JMenuItem("历史项目");
        initMenu.add(chooseFileButton);
        initMenu.add(chooseHistoryFile);
        this.setJMenuBar(jMenuBar);
        initMenu.add(new ExitItem());
        this.revalidate();
        this.repaint();
        helper.addMenuListener(new MenuListener() {
            @Override
            public void menuSelected(MenuEvent e) {
                Utils.help();
            }

            @Override
            public void menuDeselected(MenuEvent e) {
            }

            @Override
            public void menuCanceled(MenuEvent e) {
            }

        });
        jTextArea.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_ENTER) {
                    String input = jTextArea.getText();
                    String[] cmd = input.trim().split("\\s+");
                    if (repo != null) {
                        Backend.run(cmd, repo);
                        jTextArea.setText("");
                    }
                }
            }
        });

        chooseHistoryFile.addActionListener(e -> {
            List<String> historyLi = readHistory();
            if (historyLi == null) {
                JOptionPane.showMessageDialog(null, "无可选文件", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String[] options = historyLi.toArray(new String[0]);
            String input = (String) JOptionPane.showInputDialog(new JPanel(), "请选择历史项目", "选择历史项目",
                    JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
            if (input != null) {
                path = input;
                try {
                    if (path != null) {
                        repo = new Repository(path);
                        branches = repo.getBRANCH_HEADS_DIR().list();
                    }
                } catch (Exception err) {
                    err.printStackTrace();
                }
                FileListPanel fileListPanel = new FileListPanel(path, repo);
                BranchListPanel branchListPanel = new BranchListPanel(repo, branches);
                for (int i = 0; i < initMenu.getItemCount(); i++) {
                    JMenuItem item = initMenu.getItem(i);
                    if (item != null && "commit".equals(item.getText())) {
                        initMenu.remove(i);
                        break;
                    }
                }
                for (int i = 0; i < jMenuBar.getMenuCount(); i++) {
                    JMenu menu = jMenuBar.getMenu(i);
                    if (menu.getText().equals("View")) {
                        jMenuBar.remove(i);
                        break;
                    }
                }
                for (int i = 0; i < jMenuBar.getMenuCount(); i++) {
                    JMenu menu = jMenuBar.getMenu(i);
                    if (menu.getText().equals("Branch")) {
                        jMenuBar.remove(i);
                        break;
                    }
                }
                for (int i = 0; i < jMenuBar.getMenuCount(); i++) {
                    JMenu menu = jMenuBar.getMenu(i);
                    if (menu.getText().equals("Remote")) {
                        jMenuBar.remove(i);
                        break;
                    }
                }
                for (int i = 0; i < jMenuBar.getMenuCount(); i++) {
                    JMenu menu = jMenuBar.getMenu(i);
                    if (menu.getText().equals("File")) {
                        jMenuBar.remove(i);
                        break;
                    }
                }
                JMenu viewMenu = new ViewMenu(repo);
                JMenu branchMenu = new BranchMenu(branchListPanel, repo);
                JMenu repositoryMenu = new RepositoryMenu(branchListPanel, repo);
                JMenu fileMenu = new FileMenu(repo);
                jMenuBar.add(fileMenu);
                jMenuBar.add(viewMenu);
                jMenuBar.add(branchMenu);
                jMenuBar.add(repositoryMenu);
                initMenu.add(chooseFileButton);

                docPanel.removeAll();
                docPanel.add(fileListPanel);
                branchPanel.removeAll();
                branchPanel.add(branchListPanel);
                branchPanel.revalidate();
                branchPanel.repaint();
                docPanel.revalidate();
                docPanel.repaint();
                this.revalidate();
                this.repaint();
                new Thread(() -> FileWatchService.watchDirectory(path, docPanel, repo)).start();
                // new Thread(() -> {new Backend().run();}).start();
            }
        });

        chooseFileButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int option = fileChooser.showOpenDialog(this);
            if (option == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                // System.out.println("选择的文件夹: " + file.getAbsolutePath());
                path = file.getAbsolutePath();
                // 加载FileListPanel
                try {
                    if (path != null) {
                        repo = new Repository(path);
                        branches = repo.getBRANCH_HEADS_DIR().list();
                    }
                } catch (Exception err) {
                    err.printStackTrace();
                }

                FileListPanel fileListPanel = new FileListPanel(file.getAbsolutePath(), repo);
                BranchListPanel branchListPanel = new BranchListPanel(repo, branches);
                for (int i = 0; i < initMenu.getItemCount(); i++) {
                    JMenuItem item = initMenu.getItem(i);
                    if (item != null && "commit".equals(item.getText())) {
                        initMenu.remove(i);
                        break;
                    }
                }
                for (int i = 0; i < jMenuBar.getMenuCount(); i++) {
                    JMenu menu = jMenuBar.getMenu(i);
                    if (menu.getText().equals("View")) {
                        jMenuBar.remove(i);
                        break;
                    }
                }
                for (int i = 0; i < jMenuBar.getMenuCount(); i++) {
                    JMenu menu = jMenuBar.getMenu(i);
                    if (menu.getText().equals("Branch")) {
                        jMenuBar.remove(i);
                        break;
                    }
                }
                for (int i = 0; i < jMenuBar.getMenuCount(); i++) {
                    JMenu menu = jMenuBar.getMenu(i);
                    if (menu.getText().equals("Remote")) {
                        jMenuBar.remove(i);
                        break;
                    }
                }
                for (int i = 0; i < jMenuBar.getMenuCount(); i++) {
                    JMenu menu = jMenuBar.getMenu(i);
                    if (menu.getText().equals("File")) {
                        jMenuBar.remove(i);
                        break;
                    }
                }
                JMenu viewMenu = new ViewMenu(repo);
                JMenu branchMenu = new BranchMenu(branchListPanel, repo);
                JMenu repositoryMenu = new RepositoryMenu(branchListPanel, repo);
                JMenu fileMenu = new FileMenu(repo);
                jMenuBar.add(fileMenu);
                jMenuBar.add(viewMenu);
                jMenuBar.add(branchMenu);
                jMenuBar.add(repositoryMenu);
                initMenu.add(chooseFileButton);

                docPanel.removeAll();
                docPanel.add(fileListPanel);
                branchPanel.removeAll();
                branchPanel.add(branchListPanel, BorderLayout.CENTER);
                branchPanel.revalidate();
                branchPanel.repaint();
                docPanel.revalidate();
                docPanel.repaint();
                this.revalidate();
                this.repaint();
                new Thread(() -> FileWatchService.watchDirectory(path, docPanel, repo)).start();
                // new Thread(() -> {new Backend().run();}).start();
            } else {
                System.out.println("未选择文件夹");
            }
        });

        // 设置JFrame的大小
        this.setSize(800, 494);
        // 设置JFrame的关闭操作
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
}